const api = require('../../../utils/api.js');
const regeneratorRuntime = require('../../../utils/runtime.js');
const config = require('../../../utils/config.js')
const util = require('../../../utils/utils.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: {
      _id: '',
      name: '',
      campus: '',
      logo: '',
      majors: [],
      createTime: '',
      updateTime: ''
    },
    imgList: [],
    majors: [],
    isShowMajorModel: false,
    selectedMajors: [],
    changeImg: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let id = options.id;
    if (id !== undefined && id != "") {
      let res = await api.getDocById('mini_colleges',id)
    
      if (res.result.data.logo !== undefined && res.result.data.logo != '') {
        let imgList = this.data.imgList.concat({
          originPath: res.result.data.logo,
          httpPath: api.convertCloud2Http(res.result.data.logo)
        })
        console.log('imgList ->', imgList)
        this.setData({
          imgList: imgList
        })
      }

      this.setData({
        model: res.result.data,
        selectedMajors: res.result.data.majors,
      })
    }
  },

  /**
   * 保存
   * @param {*} e 
   */
  save: async function (e) {

    wx.showLoading({
      title: '保存中...',
    })
    let that = this;
    let model = this.data.model
    model.createTime = util.tsFormatTime(Date.now())
    model.updateTime = util.tsFormatTime(Date.now())
    console.log('input model ->', model)
    if (model.name === undefined || model.name == "") {
      wx.showToast({
        title: '学院名称不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    if (model.campus === undefined || model.campus == "") {
      wx.showToast({
        title: '校区不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    model.majors = this.data.selectedMajors
    if (this.data.imgList.length > 0 && this.data.changeImg) {
      let filePath = this.data.imgList[0].originPath
      let suffix = /\.[^\.]+$/.exec(filePath)[0];
      let result = await api.uploadFile('colleges/'+model.name+ '_' + model.campus + '/' + Date.now() + '.png', this.data.imgList[0].originPath)
      console.log('upload file result -> ', result)
      if (result.statusCode == 200) {
        model.logo = result.fileID
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '图片上传失败，请重试',
          icon: 'none',
          duration: 1500
        })
        return 
      }
    } else if (this.data.changeImg) {
      model.logo = ''
    }

    this.setData({
      changeImg: false
    })

    let result = await api.saveAdminDoc('mini_colleges', model)
    if (result) {
      wx.hideLoading()
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 1500
      })
    }
  },


  onDataChange: function (e) {
    console.info('data change -> ', e)
    let model = this.data.model;
    switch (e.currentTarget.id) {
      case 'name': {
        model.name = e.detail.value
        break
      }
      case 'campus': {
        model.campus = e.detail.value
        break
      }
    }
    console.info('current change -> ', model)
    this.setData({
      model: model
    })
  },

  navBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },


  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log('image -> ', res)
        this.setData({
          changeImg: true
        })
        this.setData({
          imgList: this.data.imgList.concat({
            originPath: res.tempFilePaths[0],
            httpPath: res.tempFilePaths[0]
          })
        })
      }
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },


  hideMajorModal: function (e) {
    this.setData({
      isShowMajorModel: false
    })
  },

  /**
   * 显示major窗口
   * @param {*} e 
   */
  showMajorModal: async function (e) {
    wx.showLoading({
      title: '专业加载中...',
    })

    let result = await api.getMajorList(1, {})
    let majors = []
    let selectedMajors = this.data.selectedMajors
    if (result.data.length > 0) {
      let data = result.data
      let checked = false
      for (var i = 0; i < data.length; i++) {
        checked = selectedMajors.filter(a => a == data[i].name).length > 0
        majors.push({
          name: data[i].name,
          checked: checked
        })
      }

      this.setData({
        majors: majors,
        isShowMajorModel: true,
        selectedMajors: selectedMajors
      })
    } 

    wx.hideLoading()
  },

  chooseMajorCheckbox(e) {
    let that = this
    let selectedMajors = that.data.selectedMajors
    let majors = that.data.majors;
    let name = e.currentTarget.dataset.value;
    let checked = e.currentTarget.dataset.checked;
    console.log('checked -> ', e)
    for (let i = 0; i < majors.length; i++) {
      if (majors[i].name == name) {
        majors[i].checked = !checked;
        break
      }
    }
    if (checked) {
      var index = selectedMajors.indexOf(name);
      if (index > -1) {
        selectedMajors.splice(index, 1);
      }
    }
    else {
      selectedMajors.push(name)
    }

    that.setData({
      selectedMajors: selectedMajors,
      majors: majors
    })

    console.log('selected -> ', selectedMajors)
  },

  prohibitHide: async function(e) {
    return true
  }
})